package com.lm56.common.validation.anotation.validator;

import com.lm56.common.validation.anotation.constraints.MyDateTimeValid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * Created by Kelvin Yeung on 2016/10/30.
 */
public class MyDateTimeValidator implements ConstraintValidator<MyDateTimeValid,Object> {

    private SimpleDateFormat df;


    public void initialize(MyDateTimeValid constraintAnnotation) {
       df = new SimpleDateFormat(constraintAnnotation.pattern());
    }

    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
             df.parse((String) value);
        } catch (ParseException e) {
            String messageTemplate = context.getDefaultConstraintMessageTemplate();
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(messageTemplate)
                    .addPropertyNode((String) value)
                    .addConstraintViolation();
            return false;
        }catch (Exception e){
            e.printStackTrace();
        }
        return  true;
    }
}
